package cn.anzhiyublog.staranimegallery.controller;

import cn.anzhiyublog.staranimegallery.annotation.Auth;
import cn.anzhiyublog.staranimegallery.model.domain.Tag;
import cn.anzhiyublog.staranimegallery.model.enums.Authority;
import cn.anzhiyublog.staranimegallery.model.enums.StatusCode;
import cn.anzhiyublog.staranimegallery.model.response.Response;
import cn.anzhiyublog.staranimegallery.service.TagService;
import cn.anzhiyublog.staranimegallery.util.ResultUtils;
import cn.anzhiyublog.staranimegallery.util.ThrowUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 标签控制层(获取方式在图片控制层)
 *
 * @author 安知一只鱼
 */
@RestController
@RequestMapping("/tag")
public class TagController {
    @Autowired
    private TagService tagService;

    /**
     * 新增标签
     *
     * @param tagName 标签名
     * @return 新增成功
     */
    @PostMapping("/add")
    @Auth(value = Authority.MANAGE)
    public Response<?> addTag(@RequestParam String tagName) {
        ThrowUtils.throwIf(tagName.isEmpty(), StatusCode.BAD_REQUEST, "标签名不能为空");
        tagService.add(tagName);
        return ResultUtils.success("新增成功");
    }

    /**
     * 删除标签
     *
     * @param tagName 标签名
     * @return 删除成功
     */
    @PostMapping("/delete")
    @Auth(value = Authority.MANAGE)
    public Response<?> deleteTag(@RequestParam String tagName) {
        Tag tag = tagService.getByName(tagName);
        ThrowUtils.throwIf(tag==null, StatusCode.NOT_FOUND, "标签不存在");
        ThrowUtils.throwIf(tag.getCanChange()==1, StatusCode.CONFLICT, "该标签不能被改动");
        tagService.delete(tag.getId());
        return ResultUtils.success("删除成功");
    }

    /**
     * 编辑标签
     *
     * @param oldTagName 原标签名
     * @param newTagName 新标签名
     * @return 编辑成功
     */
    @PostMapping("/edit")
    @Auth(value = Authority.MANAGE)
    public Response<?> editTag(String oldTagName, String newTagName) {
        Tag tag = tagService.getByName(oldTagName);
        ThrowUtils.throwIf(tag==null, StatusCode.NOT_FOUND, "标签不存在");
        tag.setTagName(newTagName);
        ThrowUtils.throwIf(tag.getCanChange()==1, StatusCode.CONFLICT, "该标签不能被改动");
        tagService.edit(tag.getId(), tag.getTagName());
        return ResultUtils.success("编辑成功");
    }
}
